package com.qdu.spring.blog.interceptor;

import com.qdu.spring.blog.util.AjaxResult;
import com.qdu.spring.blog.util.JsonUtils;
import com.qdu.spring.blog.util.MyConstant;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class IsLoginInterceptor extends HandlerInterceptorAdapter {
    /**
     * 进入controller层之前拦截请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception
    {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        Object user = request.getSession().getAttribute("user");

        // 如果用户还没有登录，让用户去登录
        if (user == null)
        {
            response.setContentType("text/html;charset=UTF-8");
            String ctxPath = request.getContextPath();

            if (StringUtils.isEmpty(request.getHeader(MyConstant.REQUEST_HEADER)))
            {
                response.sendRedirect(ctxPath + MyConstant.LOGIN_PATH);
            } else
            {
                //ajax请求
                try (PrintWriter out = response.getWriter())
                {
                    // 返回json格式的权限不足信息
                    out.print(JsonUtils.toJson(AjaxResult.errorInstance("需要重新登录")));
                }
            }
            return false;
        }

        return true;
    }
}
